import re
import sys
import tkinter as tk
import ast
from Constraints import Constraints
from PuzzleSolver import PuzzleSolver as Solver

class GridVisualizer(tk.Tk):
    def __init__(self, constraints, state):
        super().__init__()
        self.title("Grid Visualizer")
        self.canvas = tk.Canvas(self, width=constraints.width * 20, height=constraints.height * 20)
        self.canvas.pack()
        self.draw_grid(constraints, state)

    def draw_grid(self, constraints, state):
        cell_size = 20
        for i in range(constraints.height):
            for j in range(constraints.width):
                x1, y1 = j * cell_size, i * cell_size
                x2, y2 = x1 + cell_size, y1 + cell_size
                if state[i][j]:
                    self.canvas.create_rectangle(x1, y1, x2, y2, fill="black")
                else:
                    self.canvas.create_rectangle(x1, y1, x2, y2, fill="white")



class ListInputApp:
    def __init__(self, master):
        self.master = master
        self.master.title("列表输入应用程序")
        self.create_dimension_input()

    def create_dimension_input(self):
        self.height_var = tk.IntVar()
        self.width_var = tk.IntVar()



        tk.Label(self.master, text="行数:").grid(row=1, column=0)
        tk.Entry(self.master, textvariable=self.height_var).grid(row=1, column=1)

        tk.Label(self.master, text="列数:").grid(row=0, column=0)
        tk.Entry(self.master, textvariable=self.width_var).grid(row=0, column=1)

        tk.Button(self.master, text="下一步", command=self.create_list_input).grid(row=2, column=0, columnspan=2)

    def create_list_input(self):
        width = self.width_var.get()
        height = self.height_var.get()

        for widget in self.master.winfo_children():
            widget.destroy()

        self.entries_rows = [tk.Entry(self.master) for _ in range(width)]
        self.entries_columns = [tk.Entry(self.master) for _ in range(height)]

        # 创建列输入框
        for i, entry in enumerate(self.entries_columns):
            entry.grid(row=1, column=i)
        # 创建行输入框
        for i, entry in enumerate(self.entries_rows):
            entry.grid(row=0, column=i)


        tk.Button(self.master, text="提交", command=self.collect_data).grid(row=2, column=0,
                                                                            columnspan=max(width, height))

    @staticmethod
    def parse_list(input_str):
        # 替换中文逗号为英文逗号
        input_str = input_str.replace('，', ',')

        # 使用逗号或空格作为分隔符拆分字符串
        items = re.split(r'[,\s]\s*', input_str.strip())

        # 尝试将每个项目转换为整数
        try:
            return [int(item) for item in items if item]
        except ValueError:
            raise ValueError("输入包含非数字字符，请检查您的输入。")

    def collect_data(self):
        try:
            rows = [self.parse_list(entry.get()) for entry in self.entries_rows]
            columns = [self.parse_list(entry.get()) for entry in self.entries_columns]

            # 接下来是组合和验证逻辑...
        except ValueError as e:
            tk.messagebox.showerror("输入错误", str(e))

        data = {
            "width": len(rows),
            "height": len(columns),
            "rows": columns,
            "columns": rows
        }

        print(data)
        self.validate_json(data)

        # 在这里可以将data保存到文件或进行其他处理

    @staticmethod
    def validate_json(json_object):
        errors, instance = Constraints.validate_json(json_object)
        if errors:
            print("The configuration file is not valid.", file=sys.stderr)
            print("Errors:", file=sys.stderr)
            print("\t", end="", file=sys.stderr)
            print("\n\t".join(errors), file=sys.stderr)
            return

        solver: Solver = Solver(instance)
        solutions = solver.solve()

        first = True
        for index, solution in enumerate(solutions):
            if not first:
                print()
            first = False
            print("Solution {}/{}".format(index + 1, len(solutions)))
            print(solution)



if __name__ == '__main__':

    # 创建主窗口
    root = tk.Tk()
    app = ListInputApp(root)
    root.mainloop()
